package com.napenalki.toto.service.impl;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.napenalki.toto.service.IllegalEntryException;

public class EntityValidationHelper {

    static final <T> void validateEntity(T entity) {
        
        if (entity == null) {
            throw new IllegalEntryException("The given entity cannot be null");
        }
        
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        
        Set<ConstraintViolation<T>> violations = validator.validate(entity);
        
        if (violations.size() > 0) {
            List<String> issues = new ArrayList<String>(violations.size());
            for (ConstraintViolation<T> violation : violations) {
                issues.add(violation.getMessage());
            }
            throw new IllegalEntryException(issues);
        }

    }

    static final void validateDate(int year, int month, int day) {
        validateDate(year, month, day, 0, 0);
    }

    static final void validateDate(int year, int month, int day, int hours, int minutes) {
        try {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setLenient(false);
            cal.set(GregorianCalendar.YEAR, year);
            cal.set(GregorianCalendar.MONTH, month);
            cal.set(GregorianCalendar.DAY_OF_MONTH, day);
            cal.set(GregorianCalendar.HOUR_OF_DAY, hours);
            cal.set(GregorianCalendar.MINUTE, minutes);
            
            cal.getTime();
        } catch (Exception ex) {
            throw new IllegalEntryException("Date " + day + "." + month + "."
                    + year + " is not valid");
        }
    }


}
